﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;

namespace Server
{
    public class MQProducer
    {
        private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory()
        {
            HostName = "localhost",
            UserName = "lws-admin",
            Password = "123456",
            Port = 5672,
            VirtualHost = "lws-admin"
        };

        private const string ExchangeName = "交换机";

        private const string QueueName = "抢购队列";

        public static void SendQueueMsg(string msg = "", string QueueName = "简单队列")
        {
            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    //交换机名称，交换机类型，(durable)是否持久化，(autoDelete)是否自动删除
                    channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct, durable: true, autoDelete: false, arguments: null);

                    channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);
                    channel.QueueBind(QueueName, ExchangeName, routingKey: "简单模式");

                    var props = channel.CreateBasicProperties();
                    props.Persistent = true;
                    var msgBody = Encoding.UTF8.GetBytes($"{msg}");
                    channel.BasicPublish(exchange: ExchangeName, routingKey: "简单模式", basicProperties: props, body: msgBody);

                    channel.Close();
                }
            }
        }
    }
}
